package com.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.commonutils.results;
import com.entity.SysRole;
import com.service.SysRoleService;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author chenmo
 * @since 2021-04-26
 */
@RestController
@RequestMapping("/role")
@CrossOrigin
public class SysRoleController {
    @Resource
    private SysRoleService roleService;

    @ApiOperation("获取所有角色信息")
    @GetMapping("/getAllRole")
    public results getAllRole() {
        List<SysRole> roleList = roleService.list(null);
        return results.ok().data("roles", roleList);
    }

    @ApiOperation("分页获取所有角色信息")
    @GetMapping("/pageRole/{current}/{limit}")
    public results pageListUser(@PathVariable long current, @PathVariable long limit) {
        Page<SysRole> rolePage = new Page<>(current, limit);
        roleService.page(rolePage, null);
        long total = rolePage.getTotal();//总记录数
        List<SysRole> records = rolePage.getRecords();//数据list集合
        return results.ok().data("total", total).data("rows", records);
    }

    @ApiOperation("根据ID值获取角色信息")
    @GetMapping("/getRoleById/{id}")
    public results getUserById(@PathVariable String id){
        SysRole role = roleService.getById(id);
        return results.ok().data("role",role);
    }

    @ApiOperation("增加角色")
    @PostMapping("/addRole")
    public results addRole(@RequestBody SysRole role) {
        boolean flag = roleService.save(role);
        if (flag)
            return results.ok();
        else return results.error();
    }

    @ApiOperation("修改角色信息")
    @PostMapping("/updateRole")
    public results updateRole(@RequestBody SysRole role){
        boolean b = roleService.updateById(role);
        if (b) {
            return results.ok();
        } else
            return results.error();
    }

    @ApiOperation("删除角色")
    @DeleteMapping("/{roleID}")
    public results removeUser(@PathVariable String roleID) {
        //删除角色时，将角色关联的用户角色修改为user
        //如果是user和admin级别，则不允许删除,并提升相应信息（未实现）
        int roleid = Integer.parseInt(roleID);
        if (roleid == 1 || roleid == 2)
            return results.error("普通用户和管理员角色不能删除");
        //根据角色ID删除角色
        boolean flag1 = roleService.removeById(roleid);
        //在service层查询角色用户关联表，如果有删除角色的用户，则将用户角色更改为user级别
        boolean flag2 = roleService.changeRoleById(roleid);
        if (flag1 && flag2) {
            return results.ok();
        } else
            return results.error();
    }

    @ApiOperation(value = "根据id列表批量删除角色")
    @DeleteMapping("batchRemove")
    public results batchRemove(@RequestBody List<Integer> idList) {
        roleService.removeByIds(idList);
        return results.ok();
    }

}

